package com.atg.atgchat.init.intecepter;

import cn.hutool.extra.servlet.ServletUtil;
import com.atg.atgchat.init.common.utils.RequestContext;
import com.atg.atgchat.init.user.model.dto.RequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/*
author: atg
time: 2025/1/16 10:51
desc: 拦截收集器
*/
@Slf4j
@Component
public class CollectorInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestInfo requestInfo = new RequestInfo();
        Long uid = Optional.ofNullable(request.getAttribute("uid"))
                .map(Object::toString).map(Long::parseLong)
                .orElse(null);
        requestInfo.setUid(uid);
        String clientIP = ServletUtil.getClientIP(request);
        requestInfo.setIp(clientIP);
        RequestContext.setRequestInfo(requestInfo);
        return true;
    }
}
